<template>
  <div class="components">
    <div class="part-form">
      
      <!-- <el-select
          v-model="aaa"
          placeholder="please select locate"
            @change="onselectLan"
        >
          <el-option label="ch" value="ch" s></el-option>
          <el-option label="en" value="en"></el-option>
        </el-select> -->
      <el-form
        ref="projectRef"
        :model="models"
        label-width="120px"
        class="main-form"
        :rules="rules"
      >
        <div v-for="(stepItem, stepIndex) in projectItems" :key="stepItem">
          <!-- 循环当前项目类型的数组 多个stepItem代表不同的step，通过nextStep切换-->

          <!-- <div v-if="stepIndex + 1 == step"> -->
          <!-- 显示当前step -->
          <div
            v-for="(item, index) in stepItem"
            :key="index"
            :class="setVisable(stepIndex)"
          >
            <!-- 下面要判断当前项目,是否有显示条件,如果有,则根据条件判断结构决定是否显示 -->
            <el-form-item
              v-if="checkConditions(item, models)"
              :label="item.label"
              :prop="item.model"
            >
              <el-row v-if="item.type == 'input'" :gutter="20" class="pl-2">
                <el-col :span="16">
                  <el-input
                    v-model="models[item.model]"
                    :placeholder="item.placeholder"
                    @change="onChange(item)"
                  ></el-input>
                </el-col>
              </el-row>
              <el-row
                v-else-if="item.type == 'select-path'"
                :gutter="20"
                class="pl-2"
              >
                <el-col :span="16">
                  <el-input
                    v-model="models[item.model]"
                    placeholder=""
                    suffix-icon="Folder"
                    @change="onChange(item)"
                  />
                </el-col>
                <el-col :span="2">
                  <el-button type="info" plain @click="getDir(item.model)">{{
                    t("language.select-dir")
                  }}</el-button>
                </el-col>
              </el-row>

              <el-row
                v-else-if="item.type == 'label'"
                :gutter="20"
                class="pl-2"
              >
                <el-col :span="16">
                  <!-- <span >{{item.label}}</span> -->
                  <span>{{ item.desc }}</span>
                </el-col>
              </el-row>

              <el-row
                v-else-if="item.type == 'select'"
                :gutter="20"
                class="pl-2 pt-1"
              >
                <el-col :span="16">
                  <el-select
                    v-model="models[item.model]"
                    :placeholder="item.placeholder"
                    @change="onChange(item)"
                  >
                    <el-option
                      v-for="item in item.select"
                      :key="item.key"
                      :label="item.label"
                      :value="item.key"
                    >
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
              <el-row
                v-else-if="item.type == 'import'"
                :gutter="20"
                class="pl-2"
              >
                <el-col :span="16">
                  <!-- <b>{{ t("language.files-tobe-add") }}:</b> -->
                  {{ models["path"] }}:

                  <p v-if="models['build'] == 'qmake'">
                    main.cpp<br />
                    {{ models["projectName"] }}.pro<br />
                  </p>
                  <p v-if="models['build'] == 'cmake'">
                    CMakeLists.txt<br />
                    main.cpp<br />
                  </p>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </div>
        <!-- </div> -->
      </el-form>
    </div>
    <div class="part-footer">
      <el-button @click="onCancel()">{{ t("language.cancel") }}</el-button>
      <el-button v-if="stepMax > 1 && step > 1" @click="onNext(-1)">{{
        t("language.prev")
      }}</el-button>
      <el-button v-if="stepMax > 1 && step == 1" disabled>{{
        t("language.prev")
      }}</el-button>
      <el-button v-if="step < stepMax" @click="onNext(1)">{{
        t("language.next")
      }}</el-button>
      <el-button
        v-else-if="step == stepMax"
        type="primary"
        @click="onConfirm()"
        >{{ t("language.create") }}</el-button
      >
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, watch, ref } from "vue";
import {
  Edit,
  Setting,
  Menu,
  CirclePlus,
  Help,
  DocumentCopy,
} from "@element-plus/icons";
import { useRouter } from "vue-router";
import { getCurrentInstance, onMounted } from "@vue/runtime-core";
import { keys, messageKeys } from "@/common/define";
import { translate } from "@/common/translate";
import { checkConditions } from "@/utils/loadJson";
import { stat } from "fs";
import { ElMessageBox, ElMessage } from "element-plus";
import useLocale from '@/languages/useLocale';
// import { setLocale2 } from "@/pages/create/index";

import { toRaw } from "@vue/reactivity";
import {
  global,
  getDir,
  // 获取用户目录
  getHomeDir,
  checkData,
  createProject,
  // 是否点击保存默认路径
  onRemberDirChanged,
  // 发送消息到vscode
  postMessage,
  showError,
  // 统一监听实现
  // commonListener,
} from "@/views/components/Global";

export default defineComponent({
  name: "CreateProjectCom",
  props: {
    // itemCurrent: Object,
    projectKey: String,
    // key: String,
  },
  components: {
    Setting,
    Edit,
    Menu,
    CirclePlus,
    Help,
    DocumentCopy,
  },
  setup(props, context) {
    const propss = toRefs(props);
    const projectRef = ref(null);
    let currentInstance = "";

    onMounted(() => {
      currentInstance = getCurrentInstance();
      // initProject();
    });

    const resetForm = () => {
      console.log("resetForm");
      console.log(projectRef);
      projectRef.value.resetFields();
      // state.dataModel = []
      // state.modelMap = new Map();
      // state.step = 1;
      // state.stepMax = 1;
      // state.projectItems = [];
    };
    watch(
      () => props.projectKey,
      (val, oldVal) => {
        console.log("CreateProject watch");
        console.log(val);
        console.log(oldVal);
        state.key = val;
        if (val != oldVal) {
          initProject();
        }
      }
    );
    const state = reactive({
      // BuildList: [
      //   'qmake',
      //   'cmake'
      // ],
      step: 1, // 步骤
      stepMax: 1,

      homePath: "",
      key: propss.projectKey, //默认设置为创建C语言,
      // projectSubType: "blanktemplate",
      projectItems: [], // 通过json获得的项目数据,已经进行了多语言处理.
      // dataModel: [], // form数据项目绑定的value数组,二维数组,第一个维度是step,第二个维度为当前步骤的index
      // modelMap: new Map(), // 初始化时,将每一个model的对应的一维/二维位置都记录到这里,方便条件检查时使用.
      models: {}, // 初始化时,将每一个model初始化进来，用了给form使用和存值
      modelsPages: {}, // 存储每个字段所在页,key：字段名；value：页号（1开始）
      // projectOption: {
      //   projectName: "",
      //   projectPath: "",
      //   home: "",
      // },
      rules: {},
      error: false,
      errorMessage: "",
      projectItemsJson: require("@/json//projectItems.json"),
    });

    const {
      i18n: { t }, // 解构实例用具t 访问语言变量
      setLocale, //当前国际化
    } = useLocale();
    const router = useRouter();
    const onConfirm = () => {
      console.log("onConfirm");
      // 执行
      if (onSubmit()) {
        // 调用父亲执行页面后续操作。
        context.emit("eventCallParentConfirm", {
          projectKey: propss.projectKey,
          data: state,
        });
      }
    };
    const onCancel = () => {
      console.log("onCancel");
      // 调用父亲执行页面后续操作。
      context.emit("eventCallParentCancel", { projectKey: propss.projectKey });
    };
    const validateEmpty = (rule, value, callback) => {
      console.log("function validateEmpty");
      console.log(rule)
      console.log(value);
      if (value === "") {
        callback(new Error(rule.message !== undefined ? rule.message : t("language.errorEmpty")));
      } else {
        callback();
      }
    };
    // const validateName = (rule, value, callback) => {
    //   console.log("function validateName");
    //   console.log(state.models);
    //   if (value === "") {
    //     callback(new Error(t("language.errorProjectNameEmpty")));
    //   } else {
    //     callback();
    //   }
    // };
    // const validatePath = (rule, value, callback) => {
    //   console.log("function validatePath");
    //   if (value === "") {
    //     callback(new Error(t("language.errorProjectPath")));
    //   } else {
    //     callback();
    //   }
    // };
    // const rules = reactive({
    //   projectName: [{ required: true, validator: validateName, trigger: "blur" }],
    //   projectPath: [{ required: true, validator: validatePath, trigger: "blur" }],
    // });
    const onSubmit = () => {
      console.log("function submit data:");
      console.log(state.models);
      try {
        console.log(currentInstance.refs.projectRef);
        currentInstance.refs.projectRef.validate((valid) => {
          console.log("validate:" + valid);
          if (valid) {
            console.log(state.models);
            console.log(toRaw(state.models));
            createProject({
              type: "CREATE_PROJECT_COMPLETED",
              // projectType: state.models.projectType,
              // projectSubType: state.models.projectSubType,
              data: toRaw(state.models),
            });
            return true;
          }
        });
      } catch (e) {
        console.log(e);
      }
      return false;
    };
    /**
     * 初始化创建项目的类型
     * key 项目类型
     *     定义于 common/define.js
     */
    const initProject = () => {
      console.log("initProject");
      console.log(state.key);
      // 根据指定key获取对应的结构数据
      let currentProject = state.projectItemsJson.projects[state.key];
      console.log(currentProject);
      // state.modelMap = new Map();
      // 初始化一下关键数据容器
      state.models = { projectType: state.key };
      state.modelsPages = {};
      state.step = 1;
      state.stepMax = 1;
      // state.dataModel = [];
      if (currentProject != undefined) {
        // 找到对应结构

        // 国际化处理后并写入容器
        state.projectItems = translate(t, currentProject);
        console.log(state.projectItems);
        // let len = state.projectItems.length;
        // 获取最大分页
        state.stepMax = state.projectItems.length;
        // 初始化当前页
        state.step = 1;

        // 开始分页循环处理
        state.projectItems.forEach((stepItems, stepIndex) => {
          let stepPart = [];
          // 开始处理一页内的项目
          stepItems.forEach((stepItem, index) => {
            // var item = {
            //   value: "",
            //   stepItem: stepItem,
            // };
            // stepPart.push(item);
            // state.modelMap.set(stepItem.model, {stepIndex: stepIndex, index, index})

            // 将找到的项目，初始化入form使用的容器
            state.models[stepItem.model] =
              stepItem.default == undefined ? "" : stepItem.default;
            state.modelsPages[stepItem.model] = stepIndex + 1; // 当前字段的所在页（1开始）
            if (stepItem.type == "select") {
              // 初始化select类型的项目
             // console.log("found select :" + stepItem.select[0].key);
              let isFound = false;
              stepItem.select.forEach((select, index) => {

                if (select.key == stepItem.default) {
                  isFound = true;
                  console.log("found default " + select.key );
                }

              });
              if (isFound == true) {
                state.models[stepItem.model] = stepItem.default;
              } else {
                //找不到从select中找不到default 值的话，把select数组第一个元素作为default
                state.models[stepItem.model] = stepItem.select[0].key; 
              }
            }

            if(stepItem.isRequired == "true"){
              state.rules[stepItem.model] = [
                { required: true, 
                  validator: validateEmpty,
                  message: stepItem.requiredMsg != undefined && stepItem.requiredMsg.length > 0 ? stepItem.requiredMsg : t("language.errorName") , 
                  trigger: "blur" }
              ];
            }
          });
          // state.dataModel.push(stepPart);
        });
        getHomeDir(state.key);
        // 通知父级，初始化完成
        context.emit("eventCallParentInited", { });
      } else {
        // 报错退出
        ElMessageBox.alert("没找到对应类型项目", "Title", {
          confirmButtonText: "退出",
          callback: (action) => {
            onCancel();
          },
        });
      }
    };
    const onNext = (add) => {
      
      console.log("add: " + add + ", state.step:" + state.step + ", state.stepMax:" + state.stepMax);
      
      try {
        if (add > 0 && state.step < state.stepMax) {
          // 下一步，需要检查输入
          console.log(currentInstance.refs.projectRef);
          currentInstance.refs.projectRef.validate((valid) => {
            console.log("validate:" + valid);
            if (valid) {
              // 下一页前检查用户配置
              checkData({
                type: "CHECK_DATA",
                page: state.step,
                way: "next",
                data: toRaw(state.models),
                dataPages: toRaw(state.modelsPages),
              });
              // state.step++;
              return true;
            }
          });
        } else if (add < 0 && state.step > 0) {
          // 上一步，直接后退
          state.step--;
        }
      } catch (e) {
        console.log(e);
      }
    };
    const onChange = (item) => {
      console.log(" --- onChange");
      console.log(item);
      console.log(state.key);
      console.log(keys["KEY-QT-WIDGETS"]);
      try {
        switch (state.key) {
          case keys[""]:
            break;
          case keys["KEY-QT-WIDGETS"]:
            // QT Widgets project 特殊逻辑
            // 需要处理className和baseClass的联动逻辑
            let tmp = state.models[item.model];
            switch (item.model) {
              case "className":
                // 获得类名处理联动
                tmp = tmp.toLowerCase();
                state.models["headerFile"] = tmp + ".h";
                state.models["sourceFile"] = tmp + ".cpp";
                state.models["formFile"] = tmp + ".ui";
                break;

              case "baseClass":
                // 获得类名处理联动
                tmp = tmp.substring(1, tmp.length);
                state.models["className"] = tmp;
                tmp = tmp.toLowerCase();
                state.models["headerFile"] = tmp + ".h";
                state.models["sourceFile"] = tmp + ".cpp";
                state.models["formFile"] = tmp + ".ui";
                break;
            }

            break;
        }
        if (item.type == "input") {
        }
      } catch (e) {
        console.log(e);
      }
    };
    const setVisable = (stepIndex) => {
      // console.log(
      //   "setVisable: stepIndex:" + stepIndex + ", state.step:" + state.step
      // );
      return stepIndex + 1 == state.step ? "" : "hidden";
    };
    // const getModelValue = (model) =>{
    //   let value = ""
    //   try{
    //     let pos = state.modelMap.get(model);
    //     value = state.models[pos.stepIndex][pos.index].value;
    //   }catch(e){
    //     console.log(e)
    //   }
    //   return value;
    // }

    // const setVModel = (item) => {
    //   console.log("setVModel")
    //   console.log(item.model)
    //   console.log(state.models[item.model])
    //   console.log(state.models[item.model])
    //   return state.models[item.model]
    // }
    const getBuildPath = () => {
      postMessage({
        type: "GET_BUILD_PATH",
      });
    };
    const listenerCallback = ({ data }) => {
      console.log("CreateProjectCom addEventListener callback:");
      console.log(data);
      try {
        state.error = false;
        state.errorMessage = "";
        if (data.error == "true") {
          state.error = true;
          state.errorMessage = data.message;
        } else if (data.type === "LANGUAGE") {
          // 获取vscode语言
          console.log("LANGUAGE = " + data.value);
          // 设置插件语言
          // i18n.locale = data.value;
          setLocale(data.value);
          // 设置语言之后再进行项目初始化
          initProject();
          // switch (this.key) {
          // }
        } else if (data.type === "CONNECTION_ERROR") {
          state.error = true;
          state.errorMessage = data.err;
        } else if (data.type === messageKeys["CHOOSE_DIR"]) {
          let model = data.model;
          if(model != undefined){
            state.models[model] = data.value;
            console.log(
              "state.models[" + model + "] : " + state.models[model]
            );
          }else{
            state.models["projectPath"] = data.value;
            console.log(
              "state.models['projectPath'] : " + state.models["projectPath"]
            );
          }
        } else if (data.type === messageKeys["GET_BUILD_PATH"]) {
          // 获取数据后赋值
          console.log("state.models['projectPath'] : " + data.homeDir);
          console.log("state.models['gdbPath'] : " + data.gdbPath);
          console.log("state.models['cmakePath'] : " + data.cmakePath);
          console.log("state.models['qmakePath'] : " + data.qmakePath);
          console.log("state.models['cPath'] : " + data.cPath);
          console.log("state.models['cplusPath'] : " + data.cxxPath);

          state.models["projectPath"] = data.homeDir;
          state.models["gdbPath"] = data.gdbPath;
          state.models["cmakePath"] = data.cmakePath;
          state.models["qmakePath"] = data.qmakePath;
          state.models["cPath"] = data.cPath;
          state.models["cplusPath"] = data.cxxPath;
        } else if (data.type === messageKeys["GET_HOME_DIR"]) {
          state.homePath = data.value;
          state.models["projectPath"] = data.value;
          console.log("homePath : " + state.homePath);
          if(state.key == "java"){
            state.models["jdkPath"] = data.object.jdkPath;
          }
        } else if (data.type === "CHECK_DATA") {
          // 检查通过下一页
          if (data.error == "false") {
            state.step++;
          }
        } else if(data.type === "CONTINUE_CREATE_PROJECT")
        {
          createProject({
              type: "CONTINUE_CREATE_PROJECT",
              // projectType: state.models.projectType,
              // projectSubType: state.models.projectSubType,
              data: toRaw(state.models),
            });
        } else {
          console.log("Success!");
        }
      } catch (e) {
        console.log(e);
      } finally {
        if (state.error) {
          showError(state.errorMessage);
        }
      }
    };
    // const onselectLan = (value) => {
    //   console.log("onselect: ")
    //   console.log(value)
    //       // debugger;
    //       // i18n.locale = value;
    //   setLocale(value)
    //   initProject();
    // };
    return {
      t,
      router,
      ...toRefs(state),
      onConfirm,
      onCancel,
      getDir,
      onSubmit,
      postMessage,
      initProject,
      getHomeDir,
      checkData,
      createProject,
      onNext,
      checkConditions,
      onChange,
      setVisable,
      projectRef,
      resetForm,
      // commonListener,
      // getModelValue,
      // setVModel,
      getBuildPath,
      setLocale,
      // i18n,
      // onselectLan,
      listenerCallback,
      showError,
    };
  },
  unmounted() {
    console.log("function unmounted");
    window.removeEventListener("message", this.listenerCallback);
  },
  created() {
    try {
      console.log("function created");

      window.addEventListener("message", this.listenerCallback);

      postMessage({ type: "init" });
    } catch (e) {
      console.log(e);
    }
    // console.log(getQuery());
  },
  methods: {},
});
</script>

<style>
.el-button {
  min-width: 80px;
}
.el-input__inner {
  padding-left: 10px;
}
.el-select {
  display: block;
}
</style>
